package com.butte.flyer.admin.pool;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 对象池实例
 * @author 公众号:知了一笑
 * @since 2022-03-17 14:46
 */
public class ObjPool {
    public static void main(String[] args) throws Exception {
        // 声明对象池
        DevObjPool devObjPool = new DevObjPool() ;
        // 池中借用对象
        DevObj devObj = devObjPool.borrowObject();
        System.out.println("Idle="+devObjPool.getNumIdle()+"；Active="+devObjPool.getNumActive());
        // 使用对象
        devObj.devObjInfo();
        // 归还给对象池
        devObjPool.returnObject(devObj);
        System.out.println("Idle="+devObjPool.getNumIdle()+"；Active="+devObjPool.getNumActive());
        // 查看对象池
        System.out.println(devObjPool.listAllObjects());
    }
}
/**
 * 对象定义
 */
class DevObj {
    private static final Logger logger = LoggerFactory.getLogger(DevObj.class) ;
    public DevObj (){
        logger.info("build...dev...obj");
    }
    public void devObjInfo (){
        logger.info("dev...obj...info");
    }
}
/**
 * 对象工厂
 */
class DevObjFactory extends BasePooledObjectFactory<DevObj> {
    @Override
    public DevObj create() throws Exception {
        // 创建对象
        return new DevObj() ;
    }
    @Override
    public PooledObject<DevObj> wrap(DevObj devObj) {
        // 池化对象
        return new DefaultPooledObject<>(devObj);
    }
}
/**
 * 对象池
 */
class DevObjPool extends GenericObjectPool<DevObj> {
    public DevObjPool() {
        super(new DevObjFactory(), new GenericObjectPoolConfig<>());
    }
}
